﻿using System;
using System.Collections.Generic;
using System.Linq;
using Common;
using Common.Security;
using FlickrSL.Data;

namespace FlickrSL
{
    public static class Util
    {
        /// <summary>
        /// Generates a URL of the form: http://flickr.com/services/auth/?api_key=[api_key]&perms=[perms]&frob=[frob]&api_sig=[api_sig]
        /// </summary>
        /// <param name="sharedSecret">The Shared Secret for this application</param>
        /// <param name="apiKey">The API key for this application</param>
        /// <param name="perms">The type of permissions to request</param>
        /// <param name="frob">The frob generated for this authentication request</param>
        /// <returns>A URL that the user should be redirected to for authentication</returns>
        public static String GenerateAuthenticationUrl(String sharedSecret, String apiKey, TokenPermissions perms, String frob)
        {
            String queryString = String.Format("api_key={0}&perms={1}&frob={2}");
            queryString += "&api_sig=" + GenerateSignature(sharedSecret, queryString);

            return "http://flickr.com/services/auth/?" + queryString;
        }

        public static String GenerateSignature(String sharedSecret, String queryString)
        {
            List<String> parts = new List<String>(queryString.Split('&'));
            parts.Sort((str1, str2) => str1.Split('=')[0].CompareTo(str2.Split('=')[0]));

            String requestString = String.Join("", parts.Select(str => str.Strip('=')));

            return MD5Core.GetHashString(requestString);
        }
    }
}
